<template>
  <div
    :id="'chartMain' + chartId"
    v-loading="isVisualVappShowLoadingProgress && isLoading"
    class="chartMain multi-two-icon"
    :class="`${componentStyleClass} ${componentStyle}-Style`"
  >
    <Tooltip ref="Tooltip" :component-style="componentStyle" />
    <AdvancedLinkageToolbar :wid="widgetInstanceId" :config="config" />
    <ComponentTitle :title-text-style="getCssStyle('title')" :property="config.config.property" />
    <div
      v-show="!isNoData && !isDataAbnormal"
      :class="['displayBox', `layout_${layoutZN}`]"
      :style="{
        ...getCssStyle('grid'),
        ...boxBgColor,
        height: title ? 'calc(100% - ' + getCssStyle('title').lineHeight + ')' : '100%',
      }"
    >
      <div :class="`displayBox-main layout_${layoutZN}`">
        <div
          v-for="(item, index) in showData"
          :key="index"
          :class="
            `multi-two-icon-contentBox${chartId} ${
              config.config.property.selectedStatus ? 'contentData-hover' : ''
            } item multi-two-contentBox ${selectedIndex === index && config.config.property.selectedStatus ? 'on' : ''}`
          "
          :style="itemStyle"
          @click="emitAllMessages(item, index)"
        >
          <div v-visual-tooltip="getTooltip(item)" class="contentData">
            <div class="img" :style="style.img">
              <Icon v-if="haveIcon(item.icon)" :conf="item.icon" />
              <el-image v-else :src="getImg(item, index)" :style="style.elImage">
                <template #placeholder>
                  <div class="image-slot">
                    {{ $demoi18n('message.loading') }}
                    <span class="dot">...</span>
                  </div>
                </template>
                <template #error>
                  <div></div>
                </template>
              </el-image>
            </div>
            <div class="text">
              <span class="value" :style="{ ...(item.style ? item.style.value : {}), ...multiValStyle(item) }">
                {{ item.value }}
              </span>
              <span
                class="unit"
                :style="{
                  ...(item.style ? item.style.unit : {}),
                  ...getCssStyle('unit'),
                  ...multiValStyle(item, 'unit'),
                }"
              >
                {{ item.unit }}
              </span>
            </div>

            <div class="contentName" :style="style.contentName">
              <span class="name" :style="getCssStyle('name')">
                {{ item.alias ? item.alias : item.name }}
              </span>
            </div>
          </div>
        </div>
        <div v-if="showData.length % 2 === 1" :style="itemStyleEnd"></div>
      </div>
    </div>
    <NoData
      :isNoData="isNoData"
      :boxBgColor="boxBgColor"
      :noDataPromptType="config.config.property.noDataPromptType"
      :noDataPrompt="config.config.property.noDataPrompt"
    />
    <AbnormalData :isDataAbnormal="isDataAbnormal" :boxBgColor="boxBgColor" :abnormalType="abnormalType" />
  </div>
</template>
<script>
import AdvancedLinkageToolbar from '@/components/common/advanced-linkage/advanced-linkage-toolbar.vue';
import Icon from '@/components/common/icon/icon.vue';
import dfCssStyle from '@/components/panel-property-multi-value/cssStyle-default.js';
import chartBase from '@/mixin/chart-base.js';
import componentValueBase from '@/mixin/component-value-base.js';
import iconChartBase from '@/mixin/icon-chart-base.js';
import { convertValue } from '@/utils/util.js';
import ComponentTitle from '../common/component-title/component-title.vue';
import NoData from '../common/no-data/no-data.vue';
import AbnormalData from '../common/abnormal-data/abnormal-data.vue';
import Tooltip from '../common/tooltip/tooltip.vue';
import config from './config/config';
import { nextTick } from 'vue';

export default {
  name: 'MultiValueSingleLineWithIcon',
  components: { ComponentTitle, NoData, Tooltip, Icon, AdvancedLinkageToolbar, AbnormalData },
  mixins: [chartBase, iconChartBase, componentValueBase],
  props: ['pareentId', 'widgetId', 'widgetInstanceId', 'widgetName', 'identifier', 'layout', 'w', 'h'],
  data() {
    const _config = JSON.parse(JSON.stringify(config));
    return {
      ..._config.config.property,
      isIcon: true,
      isLoading: false,
      isNoData: false,
      orgConfig: [],
      isShow: true,
      selectedIndex: -1,
      chartId: '',
      config: null,
      title: '',
      count: 0,
      isDynamicAdapt: false,
      configData: [],
      showData: [],
      isThreshold: false,
      threshold: [],
      layoutZN: 'N',
      style: {
        light: {
          box: { backgroundColor: '#FFF', borderTop: '' },
          back: { backgroundColor: '#F5FAFF', height: '47%' },
        },
        dark: {
          box: { backgroundColor: '#0D263A', borderTop: '' },
          back: { backgroundColor: '#122E45', height: '47%' },
        },
        real: {
          box: { backgroundColor: '#232323', borderTop: '' },
          back: { backgroundColor: '#122E45', height: '47%' },
        },
      },
      titleHeight: 0,
      dfCssStyle,
      componentStyle: window._adoPremise.uc.theme,
    };
  },
  computed: {
    itemStyle() {
      return this.getItemStyle();
    },
    itemStyleEnd() {
      return this.getItemStyle(true);
    },
  },
  watch: {
    showData() {
      nextTick(() => {
        this.calcUnitRect();
      });
    },
  },
  created() {
    this.orgConfig = config;
    this.config = JSON.parse(JSON.stringify(this.orgConfig));

    this.chartId = `${this.widgetInstanceId}_01`;
  },
  mounted() {
    if (window.isLocalEnv) {
      this.loadWidget();
    }
  },
  methods: {
    emitAllMessages(item, index) {
      const mappingObj = {
        s: 'name',
        y: 'value',
      };
      this.selectedIndex = index;
      this.sendAllMessages(item, index, mappingObj);
      this.sendAdvancedLinkagge({
        s: item.name,
        y: item.orgValue,
        unit: item.unit,
      });
    },
    getImg(item, index, img = 'content') {
      const imgNum = 2;
      if (item.threImgUrl) {
        return item.threImgUrl;
      } else if (item.imgUrl) {
        return item.imgUrl;
      } else {
        return new URL(`../common/images/${img}_${this.componentStyle}_${index % imgNum}.png`, import.meta.url).href;
      }
    },

    // 初始加载时 以及 编排面更改配置时 触发
    loadWidget(pageStatus) {
      this.pageStatus = pageStatus;
      this._updateConfigProperty();
      this.updateConfigData();
      this.updateComponentByResolution();

      if (window.isLocalEnv || this.emitComponentStatus) {
        this.updateParams(pageStatus);
        if (!this.isRealTime) {
          this.debounceGetData();
        }
      }
      this.afterLoadWidget();
      nextTick(() => {
        this.calcUnitRect();
      });
    },

    // 根据分辨率来更新组件
    updateComponentByResolution() {
      nextTick(() => {
        setTimeout(() => {
          const title = document.querySelector(`#chartMain${this.chartId} .component-title`);
          this.titleHeight = title ? title.offsetHeight : 0;
          this.calcUnitRect();
        }, 500);
      });
    },

    _updateConfigProperty() {
      this.updateConfigProperty();
      const {
        data,
        isThreshold,
        threshold,
        title,
        isDynamicAdapt,
        componentStyle,
        multiSortBy = 'name',
        layoutZN = 'N',
        imgSize = 60,
      } = this.config.config.property;

      this.componentStyle = componentStyle;
      this.configData = JSON.parse(JSON.stringify(data));
      this.isThreshold = isThreshold;
      this.threshold = threshold;
      this.count = data.length;
      this.isDynamicAdapt = isDynamicAdapt;
      this.multiSortBy = multiSortBy;
      this.layoutZN = layoutZN;
      this.imgSize = imgSize;

      // 该方法在icon-chart-base.js里
      this.updateImgUrlMultiValue(this.configData);
    },
    getTooltip(item) {
      return {
        config: this.config.config.property.tooltip || {},
        vars: {
          s: item.name,
          y: item.value,
          unit: item.unit,
        },
        params: this.params,
        parentComp: this,
      };
    },
    calcUnitRect() {
      const compnt = document.getElementById(`chartMain${this.chartId}`);
      if (compnt) {
        const contentBox = compnt.getElementsByClassName('displayBox-main')[0];
        const arrW = [];
        const arrH = [];
        const units = compnt.getElementsByClassName('multi-two-contentBox');
        for (let i = 0; i < units.length; i++) {
          const contentData = units[i].getElementsByClassName('contentData')[0];
          if (contentData) {
            contentData.style = {};
          }
        }

        for (let i = 0; i < units.length; i++) {
          const contentData = units[i].getElementsByClassName('contentData')[0];
          if (contentData) {
            arrW.push(contentData.clientWidth);
            const _img = contentData.querySelector('.img') || {};
            const _text = contentData.querySelector('.text') || {};
            const contentName = contentData.querySelector('.contentName') || {};
            const imgH = _img.offsetHeight || 0;
            const textH = _text.offsetHeight || 0;
            const nameH = contentName.offsetHeight || 0;
            arrH.push(Math.ceil(imgH + textH + nameH));
          }
        }

        arrW.sort((a, b) => b - a);
        arrH.sort((a, b) => b - a);
        for (let i = 0; i < units.length; i++) {
          const contentData = units[i].getElementsByClassName('contentData')[0];
          if (contentData) {
            contentData.style.minWidth = `${arrW[0]}px`;
            contentData.style.minHeight = `${arrH[0]}px`;
          }
        }
        if (contentBox) {
          const { unitGap } = this.config.config.property || 0;
          const dataLen = this.showData.length;
          const rowNum = dataLen >= 2 ? 2 : 1;

          let columnLength;
          const x = Math.ceil(dataLen / 2);
          if (this.layoutZN === 'N') {
            columnLength = x;
          } else {
            columnLength = dataLen === 2 ? 2 : x;
          }

          contentBox.style.minWidth = `${columnLength * arrW[0] + unitGap * (columnLength - 1)}px`;
          contentBox.style.minHeight = `${rowNum * arrH[0] + unitGap * (rowNum - 1)}px`;
        }
      }
    },
    getItemStyle(isEmptyDiv = false) {
      const n = this.showData.length;
      let firstLineN = 1; // 第一行含有多少个格子
      let h = 50;
      const { unitGap } = this.config.config.property || 0;
      if (this.layoutZN === 'N') {
        firstLineN = Math.ceil(n / 2);
      }
      if (this.layoutZN === 'Z') {
        firstLineN = n === 2 ? 2 : Math.ceil(n / 2);
        if (n <= 2) {
          h = 100;
        }
      }
      const w = 100 / firstLineN;

      let bgColor = 'transparent';
      if (!isEmptyDiv) {
        const bgColorMap = {
          light: '#F5FAFF',
          dark: '#122E45',
          real: '#303030',
        };
        bgColor = bgColorMap[this.componentStyle];
      }
      const { backgroundColor } = this.config.config.property || this.getValByCompStl('#ffffff', '#0D263A', '#303030');
      const originBgColors = ['#fff', '#ffffff', '#0d263a', '#232323'];

      let boxBgColor;
      if (backgroundColor) {
        if (originBgColors.includes(backgroundColor.toLowerCase())) {
          boxBgColor = bgColor;
        } else {
          boxBgColor = backgroundColor;
        }
      } else {
        boxBgColor = bgColor;
      }

      return {
        backgroundColor: boxBgColor,
        width: `calc(${w}% - ${convertValue(unitGap)}px)`,
        height: `calc(${h}% - ${convertValue(unitGap) / 2}px)`,
      };
    },
  },
};
</script>
<style lang="less" scoped>
// 图表通用样式，主要有黑色loading 和 黑色 ‘没有数据’，样式名需一致
@import '../../common/chart.less';
</style>
<style lang="less" scoped>
@import './config/theme.less';
.multi-two-icon {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .title {
    width: 100%;
    height: 50px;
    font-size: 18px;
    position: relative;
    span {
      display: flex;
      align-items: center;
      height: 100%;
      margin-left: 5%;
    }
  }
  .displayBox {
    width: 100%;
    padding: 0 2.5%;
    padding-bottom: 20px;
    padding-top: 20px;
    height: calc(100% - 60px);
    flex: 1;
    min-height: 0;
    margin: 0 auto;
    text-align: center;
    overflow: auto;
    .displayBox-main {
      display: flex;
      flex-direction: column;
      align-content: space-around;
      justify-content: space-between;
      flex-wrap: wrap;
      width: 100%;
      height: 100%;
      overflow: hidden;
      &.layout_Z {
        flex-direction: row;
        align-content: space-between;
        justify-content: space-around;
      }
    }
    .item {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: max-content;
      .contentData {
        display: flex;
        justify-content: space-around;
        flex-direction: column;
        text-align: center;
        height: 100%;
        min-height: max-content;
        line-height: 1;
        width: max-content;
        .contentName {
          width: max-content;
          text-align: center;
          width: 100%;
        }
        .textBox {
          width: max-content;
          .text {
            width: max-content;
          }
        }
        .img {
          display: flex;
          justify-content: center;
          align-content: center;
          .el-image,
          .image-slot {
            width: 60px;
            height: 60px;
            vertical-align: middle;
          }
        }
      }
    }
  }
}
.multi-two-contentBox {
  &.contentData-hover:hover {
    background-color: var(--contentData-hover-bg-color) !important;
  }
  &.on {
    background-color: var(--content-on-bg-color) !important;
  }
}
</style>

